<template>
  <div class="invoice-main">
    <!-- <el-card class="box-card" shadow="hover">
      <el-row>
        <el-button type="primary" class="add-invoice" @click="AddInvoive">添加</el-button>
      </el-row>
    </el-card> -->


    <!-- <span class="tag" >
      <font color="black">可开票金额总计：</font>
      <font class="font_success">{{ invoiceMoneySum + '元' }}</font>
    </span> -->


    <el-popover placement="left" trigger="click">
			<template :loading="loading">
				<!-- 随便给个data就行，否则无法弹出 -->
				<el-checkbox v-model="checked" @change="allChange">全选</el-checkbox><br />
				<el-checkbox v-model="checked0">订单编号</el-checkbox><br />
				<el-checkbox v-model="checked1">专属顾问</el-checkbox><br />
				<el-checkbox v-model="checked2">订单名称</el-checkbox><br />
				<el-checkbox v-model="checked5">可开票金额</el-checkbox><br />
				<el-checkbox v-model="checked3">支付状态</el-checkbox><br />
				<el-checkbox v-model="checked4">更新时间</el-checkbox><br />

			</template>
			<el-button v-no-more-click:3000 style="float: right;margin-bottom: 5px;margin-top: 0;" slot="reference" icon='el-icon-arrow-down'>显示字段</el-button>
		</el-popover>


    <!-- 列表查找 -->
    <span class="down-execel">
      <Poptip v-model="showFilter" placement="bottom-end" @on-popper-show ='getAllAgent' @keyup.enter.native="submitsearch('conditionForm')">
        <i class="el-icon-search poptip-condition-add"></i>
        <a href="javascript:;">列表查找</a>
        <div slot="content">
          <Poptip v-model="showFilterCondition" placement="bottom-start" class='poptip-condition'>
            <i class="el-icon-plus poptip-condition-add"></i>
            <a href="javascript:;" class='poptip-condition-add'>添加过滤条件</a>

            <div slot="content" class="condition-list">
              <ul>
                <li v-for="(item, index) in columns" :key="index" class = 'poptip-condition-item' @click="addFilterCondition(item)">{{item.label}}</li>
              </ul>
            </div>
          </Poptip>

          <el-form :model="conditionForm" ref="conditionForm" label-min-width="120px" class="demo-dynamic" @submit.native.prevent >
            <el-form-item
                v-for="(condition, index) in conditionForm.condition"
                :label="condition.label"
                :key="condition.key"
                :prop="'condition.' + index + '.value'"
                :rules="{
                  required: true, message: condition.label +'不能为空', trigger: 'blur'
                }"
              >
              <el-date-picker
                v-model="updatedTime"
                type="daterange"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
                @change = 'changInput'
                @keyup.enter.native="submitsearch('conditionForm')"
                :validate-event='false'
                size="small"
                v-if='condition.label === "更新时间"'>
              </el-date-picker>

              <el-select
                size="small"
                filterable
                v-model="condition.value"
                v-else-if='condition.label === "专属顾问"'>
                <el-option
                  v-for="item in processOptions"
                  :key="item.id"
                  :label="item.email_work.split('@')[0].split('followup')[1]"
                  :value="item.id">
                </el-option>
              </el-select>

              <!-- 此处已被注释 -->
              <el-select v-else-if='condition.label === "开票金额"' v-model="condition.value" placeholder="请选择开票金额" size="small" @keyup.enter.native="submitsearch('conditionForm')">
                <el-option label="2075元" value="2075"></el-option>
                <el-option label="3075元" value="3075"></el-option>
                <el-option label="5560元" value="5560"></el-option>
              </el-select>

              <el-input v-else size="small" v-model="condition.value" @keyup.enter.native="submitsearch('conditionForm')"></el-input>
              <el-button @click.stop="removeDomain(condition)" size="mini">删除</el-button>
            </el-form-item>
          </el-form>

          <div class= 'btns'>
            <el-button @click="submitsearch('conditionForm')" size="mini" >查询</el-button>
            <el-button  @click.stop="resetForm1('conditionForm')" size="mini">重置</el-button>
          </div>
        </div>
      </Poptip>
    </span>

    <el-table
      v-if="table_show"
      id="IMTable"
      ref="orderTb"
      :data="tableData"
      border
      style="width: 100%"
      height="87%"
      @sort-change='tableSortChange'
      v-loading="loading">
      <el-table-column show-overflow-tooltip prop="id" label="ID" min-width="60" align="left" v-if='checked99'>
        <template slot-scope="scope">{{(scope.$index+1)+(currentPage-1)*tableSize}}</template>
      </el-table-column>
	    <el-table-column show-overflow-tooltip  v-if="checked0" prop="order_number" label="订单编号" min-width="300" align="left" sortable='custom'></el-table-column>
      <el-table-column show-overflow-tooltip v-if="checked2" prop="name" label="订单名称"  min-width="300" align="left" sortable='custom'>
			</el-table-column>
      <el-table-column show-overflow-tooltip v-if="checked5" prop="confirm_money" label="可开票金额(元)" min-width="180" align="left" sortable='custom'>
        <template slot-scope="scope">
          <!-- <span v-if="scope.row.invoice_record">
            {{ scope.row.invoice_record.money }}
          </span>
          <span v-else>
            -
          </span> -->
          <span>{{ scope.row.confirm_money }}</span>
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip v-if="checked3" prop="consumer_pay_status" label="支付状态" min-width="150" align="left" sortable='custom'>
        <template slot-scope="scope">
          <!-- {{ scope.row.consumer_pay_status == 1 ? '已缴费' : '未缴费'  }} -->
          <span :class='scope.row.consumer_pay_status == 1 || scope.row.consumer_pay_status == 0 ? "font_success" : "font_danger"'>
            {{ scope.row.consumer_pay_status| payStatus }}
          </span>
        </template>
			</el-table-column>
      <el-table-column show-overflow-tooltip v-if="checked1" prop="process" label="专属顾问" min-width="150" align="left" sortable='custom'>
				<template slot-scope="scope">
					<!-- <div class="more">{{scope.row.process.name}}</div> -->
					<div class="more">
						<span style="margin-right: 10px" v-if=" scope.row.order && scope.row.order.process"> {{ scope.row.order.process.email_work.split("@")[0].split("followup")[1] }} </span>
            <Tooltip  v-if="scope.row.order && scope.row.order.process"  content="点我留言">
							<i class="el-icon-chat-dot-round leaveWord" @click.stop="leaveWord(scope.row, 'process')"></i>
						</Tooltip>
					</div>
				</template>
			</el-table-column>

      <el-table-column show-overflow-tooltip v-if="checked4" prop="updated_at" label="更新时间" min-width="250" align="left" sortable='custom'>
			</el-table-column>

      <el-table-column show-overflow-tooltip label="操作" width="180" fixed="right" align="center" v-if="checked99">
        <template slot-scope="scope">
          <el-button v-no-more-click:3000 style="margin-bottom: 5px;" size="mini" type="primary" @click.stop="isInvoice(scope.row)"
					:disabled="(scope.row.invoice_record && scope.row.invoice_record.status=='等待开票')">申请开票</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      class="pagination"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="pageSizes"
      :page-size="Number(pageSize)"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>

    <!-- 弹出框 -->
    <el-dialog :title="dialogTitle" center :visible.sync="dialogFormVisible" :before-close="handleClose">
      <el-form :model="form" :rules="rules" ref="ruleForm">
        <el-form-item label="抬头" prop="taitou" v-show="!form.id" >
          <el-autocomplete
            v-model="form.taitou"
            :fetch-suggestions="querySearch"
            :trigger-on-focus="false"
            placeholder="请输入发票抬头，必填项"
            @select="handleSelect"
          >
            <template slot-scope="{ item }">
              <div class="name">{{ item.taitou }}</div>
            </template>
          </el-autocomplete>
          <!-- <el-input v-model="form.taitou" autocomplete="off" placeholder="请输入发票抬头，必填项"></el-input> -->
        </el-form-item>

        <el-form-item label="抬头" v-show="form.id" prop="taitou" >
          <el-input v-model="form.taitou" autocomplete="off" placeholder="请输入抬头"></el-input>
        </el-form-item>
        <el-form-item label="税号" v-show="!form.id" prop="tariff_number">
          <el-autocomplete
            v-model="form.tariff_number"
            :fetch-suggestions="querySearchBytariff"
            :trigger-on-focus="false"
            placeholder="请输入税号，必填项"
            @select="handleSelect">
            <template slot-scope="{ item }">
              <span class="addr">{{ item.tariff_number }}</span>
            </template>
          </el-autocomplete>
          <!-- <el-input v-model="form.tariff_number" autocomplete="off" placeholder="请输入18位税号，必填项"></el-input> -->
        </el-form-item>
        <el-form-item label="地址及电话">
          <el-input v-model="form.add_tel" autocomplete="off" placeholder="请输入地址及电话，非必填项"></el-input>
        </el-form-item>
        <el-form-item label="开户行及银行卡号">
          <el-input v-model="form.bank_card" autocomplete="off" placeholder="开户行及银行卡号，非必填项"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-no-more-click:3000 @click="handleClose">取 消</el-button>
        <el-button v-no-more-click:3000 type="primary" @click="submitForm('ruleForm')">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 申请开票弹出框 -->
		<el-dialog title="申请开票" center :visible.sync="showInvoice" class='applyBilling' @open='openInv'>
			<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-min-width="150px" class="demo-ruleForm">
				<el-form-item label="申请人" prop="name">
					<el-input disabled v-model="ruleForm.name" placeholder="请正确填写联络人姓名"></el-input>
				</el-form-item>
				<el-form-item label="申请人电话" prop="phone">
					<el-input disabled v-model="ruleForm.phone" placeholder="请仔细核对申请人电话"></el-input>
				</el-form-item>
				<el-form-item label="申请人邮箱" prop="email">
					<el-input disabled v-model="ruleForm.email" placeholder="请仔细核对申请人邮箱，并确保邮箱可用。"></el-input>
				</el-form-item>
				<el-form-item label="开票金额" prop="money">
					<el-input v-model="ruleForm.money" placeholder="开票金额"></el-input>
				</el-form-item>
				<el-form-item label="缴费渠道" prop="channel">
					<el-select v-model="ruleForm.channel" placeholder="请选择该案件的缴费渠道">
						<el-option label="银行转账" value="银行转账"></el-option>
						<el-option label="微信" value="微信"></el-option>
						<el-option label="支付宝" value="支付宝"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="抬头" prop="taitou">
					<el-autocomplete
            label="抬头"
            v-model="ruleForm.taitou"
            :fetch-suggestions="querySearch"
            :trigger-on-focus="false"
					  placeholder="请输入发票抬头"
            @select="handleSelect3">
						<template slot-scope="{ item }">
							<div class="name">{{ item.taitou }}</div>
						</template>
					</el-autocomplete>
					<!-- <el-select v-model="ruleForm.invoice" placeholder="请选择该案件的发票信息">
						<el-option v-for="(item,index) in invoiceArr" :label="item.taitou" :value="item.id"></el-option>
					</el-select> -->
				</el-form-item>
				<el-form-item label="税号" prop="invoice">
					<el-autocomplete
            label="税号"
            v-model="ruleForm.invoice"
            :fetch-suggestions="querySearchBytariff"
            :trigger-on-focus="false"
					  placeholder="请输入税号"
            @select="handleSelect">
						<template slot-scope="{ item }">
							<span class="addr">{{ item.tariff_number }}</span>
						</template>
					</el-autocomplete>
				</el-form-item>
				<el-form-item label="纸质文件邮寄地址" prop="send_addr">
					<el-input v-model="ruleForm.send_addr" placeholder="请填写纸质文件邮寄地址"></el-input>
				</el-form-item>
				<el-form-item label="地址及电话" prop="add_tel">
					<el-input v-model="ruleForm.add_tel" placeholder="请填写地址及电话"></el-input>
				</el-form-item>
				<el-form-item label="开户行及银行卡号" prop="bank_card">
					<el-input v-model="ruleForm.bank_card" placeholder="请填写开户行及银行卡号"></el-input>
				</el-form-item>
				<center class="submit-btn">
					<el-button v-no-more-click:3000 @click="showInvoice=false">取消</el-button>
					<el-button v-no-more-click:3000 type="primary" @click="invoicingNext('ruleForm')">下一步</el-button>
				</center>
			</el-form>
		</el-dialog>

		<!-- 确认开票信息弹出框 -->
		<el-dialog title="确认开票信息" center :visible.sync="showInvoice2" class='applyBilling'>
			<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-min-width="150px" class="demo-ruleForm">
				<el-form-item label="申请人" prop="name">
					<el-input disabled v-model="ruleForm.name" placeholder="请正确填写联络人姓名"></el-input>
				</el-form-item>
				<el-form-item label="申请人电话" prop="phone">
					<el-input disabled v-model.number="ruleForm.phone" placeholder="请仔细核对申请人电话"></el-input>
				</el-form-item>
				<el-form-item label="申请人邮箱" prop="email">
					<el-input disabled v-model="ruleForm.email" placeholder="请仔细核对申请人邮箱，并确保邮箱可用。"></el-input>
				</el-form-item>
				<el-form-item label="开票金额" prop="money">
					<el-input disabled v-model="ruleForm.money" placeholder="开票金额"></el-input>
				</el-form-item>
				<el-form-item label="缴费渠道" prop="channel">
					<el-select disabled v-model="ruleForm.channel" placeholder="请选择该案件的缴费渠道">
						<el-option label="银行转账" value="银行转账"></el-option>
						<el-option label="微信" value="微信"></el-option>
						<el-option label="支付宝" value="支付宝"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="抬头" prop="taitou">
					<el-autocomplete disabled label="抬头" v-model="ruleForm.taitou" :fetch-suggestions="querySearch" :trigger-on-focus="false"
					 placeholder="请输入发票抬头" @select="handleSelect">
						<template slot-scope="{ item }">
							<div class="name">{{ item.taitou }}</div>
						</template>
					</el-autocomplete>

					<!-- <el-select v-model="ruleForm.invoice" placeholder="请选择该案件的发票信息">
						<el-option v-for="(item,index) in invoiceArr" :label="item.taitou" :value="item.id"></el-option>
					</el-select> -->
				</el-form-item>
				<el-form-item label="税号" prop="invoice">
					<el-autocomplete disabled label="税号" v-model="ruleForm.invoice" :fetch-suggestions="querySearchBytariff"
					 :trigger-on-focus="false" placeholder="请输入税号" @select="handleSelect">
						<template slot-scope="{ item }">
							<span class="addr">{{ item.tariff_number }}</span>
						</template>
					</el-autocomplete>
				</el-form-item>
				<el-form-item label="纸质文件邮寄地址" prop="send_addr">
					<el-input disabled v-model="ruleForm.send_addr" placeholder="请填写纸质文件邮寄地址"></el-input>
				</el-form-item>
				<el-form-item label="地址及电话" prop="add_tel">
					<el-input disabled v-model="ruleForm.add_tel" placeholder="请填写地址及电话"></el-input>
				</el-form-item>
				<el-form-item label="开户行及银行卡号" prop="bank_card">
					<el-input disabled v-model="ruleForm.bank_card" placeholder="请填写开户行及银行卡号"></el-input>
				</el-form-item>
				<center class="submit-btn">
					<el-button v-no-more-click:3000 @click="showInvoice=true;showInvoice2=false;">上一步</el-button>
					<el-button v-no-more-click:3000 type="primary" @click="submitForm3('ruleForm')">提交</el-button>
				</center>
			</el-form>
		</el-dialog>

    <!-- 留言输入框 -->
    <leaveWordDialog ref='leaveWordDialog' />
    <!-- 留言消息框 -->
    <promptMessage ref='promptMessage' />
  </div>
</template>
<script>
import promptMessage from '~/components/promptMessage'
import leaveWordDialog from '~/components/leaveWordDialog'
import fncSearch from '~/components/searchSrceen/fnc-search.js'

export default {
  name: "invoicesManagement",
  data() {
    return {
      table_show: true,
      checked: true,
			checked0: true,
      checked1: true,
      checked2: true,
      checked3: true,
      checked4: true,
      checked5: true,
      checked6: true,
      checked7: true,
      checked8: true,
      checked9: true,
      checked10: true,
      checked11: true,
      checked99: true,
      tableData: [],
      routeid: 'canBeInvoice',
      dialogFormVisible: false,
      changeType:'add',
      form: {},
      dialogTitle: "添加发票信息",
      restaurants: [], //发票抬头匹配
      restaurantsBytariff: [], // 税号匹配
      tableSize: 10, //一页几条
      tableStart: 0, //table数组过滤的第一条索引
      tableEnd: 10, //table数组过滤的最后一条索引
      currentPage: 1, //目前在第几页
      loading: true,
      pageSizes: [25, 50], //一页可以几条
      pageSize: 25, //一页可以几条
      total:0,
      baseUrl: global.baseurl,
      showFilter: false, // 控制显示筛选条件
      showFilterCondition: false,
      conditionForm: {
        condition: []
      }, //筛选条件
      columns: [
        {
          label: '订单编号',
          id: 1,
          parameter: 'order_number',
        },
        {
          label: '订单名称',
          id: 2,
          parameter: 'name',
        },
        {
          label: '可开票金额',
          id: 6,
          parameter: 'confirm_money',
        },
        // {
        //   label: '支付状态',
        //   id: 3,
        //   parameter: 'consumer_pay_status',
        // },
        {
          label: '专属顾问',
          id: 4,
          parameter: 'process_id',
        },
        {
          label: '更新时间',
          id: 5,
          parameter: 'updated_at',
        },

      ],
      lastTime: 0,
      searchValue: '',
      refund_at: [],
      ticket_at: [],
      updatedTime:[],
      fileArr: [],
      paramsByInv: {
        consumer_pay_status: 1,
        status: '等待提交国知局,已提交国知局,等待答复,等待补正,已答复,已补正,驳回,授权',
        can_invoice: 1
      },
      showRefund: false,
      showRefund2: false,
      ruleForm2: {
        card: '',
        name: '',
        bank: ''
      },
      rules: {
        name: [{
          required: true,
          message: '请填写申请人姓名',
          trigger: 'blur'
        }],
        phone: [{
          required: true,
          validator: function(rule, value, callback) {
            if (value === '') {
              callback(new Error('请填写申请人电话'));
            } else if (!(/^1[3456789]\d{9}$/.test(value))) {
              callback(new Error('申请人电话格式错误'));
            } else {
              callback();
            }
          },
          trigger: 'blur'
        }],
        email: [{
          required: true,
          validator: function(rule, value, callback) {
            if (value === '') {
              callback(new Error('请填写申请人邮箱'));
            } else if (!(/^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/.test(value))) {
              callback(new Error('申请人邮箱格式错误'));
            } else {
              callback();
            }
          },
          trigger: 'blur'
        }],
        channel: [{
          required: true,
          message: '请选择该案件的缴费渠道',
          trigger: 'change'
        }],
        taitou: [{
          required: true,
          message: '请选择抬头',
          trigger: 'change'
        }],
        invoice: [{
          required: true,
          message: '请选择税号',
          trigger: 'change'
        }],
        money: [{
          required: true,
          validator: function(rule, value, callback) {
            if (value === '') {
              callback(new Error('请填写开票金额'));
            } else if (!Number(value)) {
              callback(new Error('开票金额只能是数字'));
            } else {
              callback();
            }
          },
          trigger: 'blur'
        }],
        // send_addr: [{
        // 	required: true,
        // 	message: '请填写纸质文件邮寄地址',
        // 	trigger: 'change'
        // }]
      },
      rules2: {
        card: [{
          required: true,
          message: '请填写银行卡号',
          trigger: 'blur'
        },
        {
          type: 'number', message: '银行卡号必须为数字值', trigger: 'blur'
        }],
        name: [{
          required: true,
          message: '请填写持卡人姓名',
          trigger: 'blur'
        }],
        bank: [{
          required: true,
          message: '请填写银行支行地址',
          trigger: 'blur'
        }]
      },
      refundID: '',
      radio: '1',
      showInvoice: false,
      showInvoice2: false,
      ruleForm: {
        name: '',
        phone: '',
        email: '',
        channel: '',
        taitou: '',
        invoice: '',
        add_tel: '',
        bank_card: '',
        money: '',
        send_addr:''
      },
      tableSelectRow: {},
      finalsID: '',
      processOptions: [],
      invoiceMoneySum: ''
      // isShowRefund: false,
    };
  },
  components: {
    promptMessage,
    leaveWordDialog,
    fncSearch
  },
  watch: {
    selectArr(val) {
      this.table_show = false
      this.$nextTick(() => {
        this.table_show = true
      })
      setTimeout(() => {
        this.$nextTick(() => {
          this.gwm()
        })
      }, 300)
      if (val.some(v => v == false)) {
        this.checked = false
      } else {
        this.checked = true
      }
      if (val.every(v => v == false)) {
        this.checked99 = false
      } else {
        this.checked99 = true
      }
    },
    // 判断抬头为空时 税号也置空
    'ruleForm.taitou':{
      handler: function (newVal, oldVal){
        if (newVal == '') {
          this.ruleForm.invoice = ''
        }
      },
      deep: true
    }
  },
  computed: {
    isShowRefund () {
      if(this.radio == '1') {
        return false
      } else {
        return true
      }
    },
    selectArr() {
      let arr = [this.checked0, this.checked1, this.checked2, this.checked3, this.checked4, this.checked5]
      return arr
    }
  },
  created() {
    this.getInvoiceList();
    this.getAllInv();
  },
  methods: {
    gwm() {
				//水印,非管理员要设置
				if (this.$store.state.user.role_id != 1
					&& this.$route.path != '/admin/register'
					&& this.$route.path != '/admin/personalCenter/dstribution'
					&& this.$route.path != '/admin/personalCenter/myPurse'
					&& this.$route.path != '/admin/activityList/activityConfig'
					&& this.$route.path != '/admin/activityList/sysConfig'
					&& this.$route.path !='/admin/login'
					&& this.$route.path != '/admin/agentImprove'
					&& this.$route.path != '/order/login') {
					let that = this;
					let gwm = require('gwm');
					gwm.creation({
						'txt': that.$store.state.user.name,
						'container': '.el-table', //#gwm
						'fontSize': 40
					})
				}
			},
    allChange(val) {
      if(val) {
        this.checked0 = true;
        this.checked1 = true;
        this.checked2 = true;
        this.checked3 = true;
        this.checked4 = true;
        this.checked5 = true;
        this.checked6 = true;
        this.checked7 = true;
        this.checked8 = true;
        this.checked9 = true;
        this.checked10 = true;
        this.checked11 = true;
      } else {
        this.checked0 = false;
        this.checked1 = false;
        this.checked2 = false;
        this.checked3 = false;
        this.checked4 = false;
        this.checked5 = false;
        this.checked6 = false;
        this.checked7 = false;
        this.checked8 = false;
        this.checked9 = false;
        this.checked10 = false;
        this.checked11 = false;
      }
    },
    leaveWord (row, role) {
      this.$refs.leaveWordDialog.showLeaveWord(row, role)
    },
    getInvoiceList() {
      let that = this;
      that.$axios
        .get("api/consumer/patent", {
          params: {
            consumer_pay_status: 1,
            status: '等待提交国知局,已提交国知局,等待答复,等待补正,已答复,已补正,驳回,授权',
            can_invoice: 1,
            sort_str: 'created_at',
            sort_order: 'desc'
          }
        })
        .then(res => {
          that.loading = false;
          if (res.data.code == 200) {
            this.tableData = res.data.data;
            this.pageSize = res.data.page.per_page;
            this.tableSize = res.data.page.per_page;
            this.tableEnd = res.data.page.per_page;
            this.total = res.data.page.total;
            this.invoiceMoneySum = res.data.invoiceTotalMoney
            for (let i = 0; i < this.tableData.length; i++) {
              this.imgs(this.tableData[i])
            }

          } else {
            this.$message.error("错误，请重试");
          }
        })

        .catch(err => {
          this.$message.error(err);
        });
    },
    //添加
    AddInvoive() {
      this.changeType = 'add'
      this.dialogTitle = "添加发票信息";
      this.dialogFormVisible = true;
    },
    //修改
    editInvoice(val) {
      this.form = val;
      this.dialogTitle = "修改发票信息";
      this.dialogFormVisible = true;
      this.changeType = 'edit'
    },
    //将数据提交给后台(添加/修改)
    submitForm(formName) {
      //验证通过
      let that = this;
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (this.changeType == 'edit') {
            //修改
            that.$axios
              .put(
                "api/consumer/" + that.form.id + "/updateInvoice",
                {
                  invoice: that.form.id,
                  taitou: that.form.taitou,
                  add_tel: that.form.add_tel,
                  bank_card: that.form.bank_card
                }
              )
              .then(res => {
                if (res.data.code == 200) {
                  this.$message.success("修改成功");
                  this.resetForm("ruleForm");
                  this.getInvoiceList();
                  this.getAllInv();
                }
              })
              .catch(err => {
                this.$message.error(err);
              });


          } else  {
            //添加
            var user = that.$store.state.user;
            that.form.consumer_id = user.id;
            that.$axios
              .post("/api/consumer/addInvoice", that.form)
              .then(res => {
                if (res.data.code == 200) {
                  that.$message.success("添加成功");
                  that.getInvoiceList();
                  this.resetForm("ruleForm");
                } else {
                  that.$message.error(res.data.message);
                  this.resetForm("ruleForm");
                }
              })
              .catch(err => {
                that.$message.error("添加失败");
                that.dialogFormVisible = false;
              });
          }
        } else {
          this.$message.error("信息填写错误，请重新输入");
        }
      });
    },

    //获取所有代理人
    getAllAgent() {
      this.$axios.get('api/user/process')
        .then(res => {
          if (res.data.code == 200) {
            this.processOptions = res.data.data
          }
        })
        .catch(err => {
          this.$message({
            type: "err",
            message: err
          })
        })
    },

    //删除发票
    delInvoices(val) {
      this.$confirm("是否删除该发票?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        center: true,
        type: "warning"
      })
        .then(() => {
          this.$axios
            .delete(
              "api/consumer/" + val.id + "/deleteInvoice",
              {
                invoice: val.id
              }
            )
            .then(res => {
              if (res.data.code == 200) {
                this.$message.success("删除成功");
                this.resetForm("ruleForm");
                this.getAllInv();
              } else {
                this.$message.error("删除失败，请重试");
              }
            })
            .catch(err => {
              this.$message.error(err);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    //关闭弹出层
    handleClose() {
      this.resetForm("ruleForm");
    },
    //重置数据
    resetForm(formName) {
      this.dialogFormVisible = false;
      this.form = {};
      this.$refs[formName].resetFields();
      this.getInvoiceList();
    },
    //获取所有发票信息
    getAllInv() {
      this.$axios
        .get("api/inv")
        .then(({ data }) => {
          let obj = data.data;
          for (const i in obj) {
            obj[i].value = obj[i].taitou;
          }
          this.restaurants = obj;
        })
        .catch(err => {
          this.$message.error(err);
        });
    },
    //输入抬头模糊匹配
    querySearch(queryString, cb) {
      var restaurants = this.restaurants;
      var results = [];
      if (restaurants.length > 0) {
        for (const i in restaurants) {
          restaurants[i].value = restaurants[i].taitou
        }
        results = results = queryString
          ? restaurants.filter(this.createFilter(queryString))
          : restaurants;
      }
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    //税号模糊匹配
    querySearchBytariff(queryString, cb) {
      var restaurants = this.restaurants;
      var results = [];
      if (restaurants.length > 0) {
        //value改为税号
        for (const i in restaurants) {
          restaurants[i].value = restaurants[i].tariff_number
        }
        results = results = queryString
          ? restaurants.filter(this.createFilter(queryString))
          : restaurants;
      }
      // 调用 callback 返回建议列表的数据
      cb(results);
    },

    //匹配
    createFilter(queryString) {
      return restaurant => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) >= 0
        );
      };
    },
    //模糊匹配赋值
    handleSelect(item) {
      var obj = {
        taitou: item.taitou,
        tariff_number: item.tariff_number,
        bank_card: item.bank_card,
        add_tel: item.add_tel,
        invoice: item.tariff_number
      };
      this.form = obj
      this.$refs["ruleForm"].clearValidate();
    },
    handleSelect3(item) {
      this.ruleForm.invoice = item.tariff_number
      this.ruleForm.add_tel = item.add_tel
      if (item.bank_card) {
        this.ruleForm.bank_card = item.bank_card
      }
      this.$refs["ruleForm"].clearValidate();
    },

    //选择一页几条
    handleSizeChange(size) {
      this.paramsByInv.perPage = size
      this.paramsByInv.page = 1
      this.$axios.get('/api/consumer/patent',{
        params: this.paramsByInv
        }
      )
      .then(res => {
        this.tableData = res.data.data;
        this.pageSize = res.data.page.per_page;
        this.tableSize = res.data.page.per_page;
        this.tableEnd = res.data.page.per_page;
        this.total = res.data.page.total;
      })
    },
    //选择第几页
    handleCurrentChange(val) {
      this.currentPage = val;
      let params =  this.paramsByInv
      let page = val;
      let that = this;
      that.$axios.get('api/consumer/patent?page='+page, {
        params
      })
      .then(res => {
        that.loading = false;
        that.tableData = res.data.data;
        this.pageSize = res.data.page.per_page;
        this.tableSize = res.data.page.per_page;
        this.tableEnd = res.data.page.per_page;
        this.total = res.data.page.total;
        for (let i = 0; i < this.tableData.length; i++) {
          this.imgs(this.tableData[i])
        }
      })
    },

    submitsearch(formName) {
				let that = this
				this.$refs[formName].validate((valid, prop) => {
				// this.$refs[formName].clearValidate();
					let props = []
					for (let k in prop) {
						props.push(prop[k][0].field)

						if (prop[k][0].message = '提交时间不能为空') {
							if (that.submitTime) {
								if (that.submitTime.length > 0) {
									that.$refs[formName].clearValidate([prop[k][0].field])
									// that.search()
									let timeIndex = props.indexOf('提交时间不能为空')
									props.splice(timeIndex, 1)
								}
							} else {
								return false
							}
						}

					}
					if (props.length) {
						that.$refs[formName].validateField(props, (valid2) => {
							if(valid2) {
								return false;
							} else {
								that.search()
                this.showFilter = false
							}

						})
					} else {
						that.search()
            this.showFilter = false
					}
        })
			},
    search() {
      this.currentPage = 1
      for (var i = 0; i < this.conditionForm.condition.length; i++) {
        let a = this.conditionForm.condition[i].parameter
        this.paramsByInv[a] = this.conditionForm.condition[i].value

        if (this.conditionForm.condition[i].parameter === 'updated_at') {
          this.paramsByInv.submit_start_time = this.updatedTime[0]
          this.paramsByInv.submit_end_time = this.updatedTime[1]
        }
      }

      delete this.paramsByInv.sort_str
      delete this.paramsByInv.sort_order
      this.$refs['orderTb'].clearSort()

      let that = this;
      that.loading = true;
      that.$axios
        .get("api/consumer/patent", {
          params: this.paramsByInv
        })
        .then(res => {
          that.loading = false;
          if (res.data.code == 200) {
            this.tableData = res.data.data;
            this.pageSize = res.data.page.per_page;
            this.tableSize = res.data.page.per_page;
            this.tableEnd = res.data.page.per_page;
            this.total = res.data.page.total;
            for (let i = 0; i < this.tableData.length; i++) {
              this.imgs(this.tableData[i])
            }
          } else {
            this.$message.error("错误，请重试");
          }
        })
        .catch(err => {
          this.$message.error(err);
        });

    },

    // 添加条件筛选
    addFilterCondition(item) {
      let filterItem = {
        value: '',
        label: item.label,
        parameter: item.parameter,
        key: Date.now()
      }
      if (this.conditionForm.condition.length > 0) {
      let conditionlabels = []
      for(let i = 0; i < this.conditionForm.condition.length; i++) {
        conditionlabels.push(this.conditionForm.condition[i].label)
      }
        let Check = conditionlabels.indexOf(item.label)
        Check == -1 ? this.conditionForm.condition.push(filterItem) : this.$message.error('请勿重复添加')
      } else {
        this.conditionForm.condition.push(filterItem)
      }

      this.showFilterCondition = false;

    },

    resetForm1(formName) {
      this.showFilter = true
      this.$refs['orderTb'].clearSort()
      this.conditionForm.condition.forEach(v => {
        if (v.value) {
          v.value = null
        }
      });
      this.updatedTime = []
      this.paramsByInv = {
        consumer_pay_status: 1,
        status: '等待提交国知局,已提交国知局,等待答复,等待补正,已答复,已补正,驳回,授权',
        can_invoice: 1
      }
      this.$nextTick(() => {
        this.$refs[formName].clearValidate()
      })
      // this.getInvoiceList()
      // this.showFilter = false
      // this.showFilterCondition = false

    },
    removeDomain(item) {
      this.showFilter = true
      delete this.paramsByInv[item.parameter]
      let index = this.conditionForm.condition.indexOf(item)
      if (index !== -1) {
        this.conditionForm.condition.splice(index, 1)
      }
      if (item.label === '更新时间') {
          this.updatedTime = []
          delete this.paramsByInv.submit_start_time
          delete this.paramsByInv.submit_end_time
      }
      this.search()
    },
    changInput () {
      this.$refs['conditionForm'].clearValidate();
    },
    imgs (data) {
      //文件 切分组件
      if (data.path == null || data.path == "") {} else {
        let file_Arr = data.path.split("&");
        data.fileArr = [];
        for (const i in file_Arr) {
          let itemobj = {
            id: i + 1,
            path: file_Arr[i],
            file: ''
          };
          let itemArr = itemobj.path.split("/")
          itemobj.path = itemArr[itemArr.length - 1]
          itemobj.file = itemArr.slice(0, 2).join("/");
          data.fileArr.push(itemobj);
        }
      }
      if (data.review_file == null || data.review_file == "") {} else {
        let file_Arr = data.path.split("&");
        data.reviewFile = [];
        for (const i in file_Arr) {
          let itemobj = {
            id: i + 1,
            path: file_Arr[i],
            file: ''
          };
          let itemArr = itemobj.path.split("/")
          itemobj.path = itemArr[itemArr.length - 1]
          itemobj.file = itemArr.slice(0, 2).join("/");
          data.reviewFile.push(itemobj);
        }
      }
    },
    isRefund(row) {
      let that = this;
      this.$confirm('<div id="myOrder"><div class="tableTitle"><span class="midText">' +
        '<h3 class="center-title">退费须知</h3>' +
        '</span></div>' +
        '<center>' +
        '<b class="center-title">（仅限已缴费用户使用，<b class="center-title2">未缴费用户请勿申请</b>）</b>' +
        '</center>' +
        '<br />' +
        '<b class="center-title3">退费方式为原路返回，即退回到缴费渠道，例如用微信缴费，则退回到微信缴费账户；退费截图发送至联络人邮箱</b><br />' +
        '#有疑问请联系：严经理，13164620214</div>', '', {
          dangerouslyUseHTMLString: true,
          confirmButtonText: '申请退款',
          cancelButtonText: '取消',
          center: true
        })
      .then(() => {
        that.refund(row.id);
      })
      .catch(action => {})
    },
    refund(id) {
      this.showRefund = true;
      this.refundID = id;
      // this.refundIndex = index;
      //this.tableData[index].invoice_record.refund = '等待退款';
    },
    submitForm2(formName) {
      let that = this;
      if (this.isShowRefund) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            that.$axios.put('/api/consumer/refund/' + that.refundID, {
              invoiceRecord: that.refundID,
              card: that.ruleForm2.card,
              name: that.ruleForm2.name,
              bank: that.ruleForm2.bank,
            })
            .then(res => {
              if (res.data.code == 200) {
                that.$message({
                  message: '申请退款成功，请等待处理结果！',
                  type: 'success',
                  duration: 3000
                });
                that.getInvoiceList()
                // that.verify = false
                //不再显示对应列的“退款申请”按钮
                // this.tableData[this.refundIndex].invoice_record.invoice_number = null
                that.showRefund = false;
                that.showRefund2 = false;
              } else {
                that.$message({
                  message: res.data.message,
                  type: 'error'
                });
              }
            })
          } else {
            return false;
          }
        });
      } else {
        that.$axios.put('/api/consumer/refund/' + that.refundID, {
            invoiceRecord: that.refundID
            })
          .then(res => {
            if (res.data.code == 200) {
              that.$message({
                message: '申请退款成功，请等待处理结果！',
                type: 'success',
                duration: 3000
              });
              that.getInvoiceList()
              // that.verify = false
              //不再显示对应列的“退款申请”按钮
              // this.tableData[this.refundIndex].invoice_record.invoice_number = null
              that.showRefund = false;
              that.showRefund2 = false;
            } else {
              that.$message({
                message: res.data.message,
                type: 'error'
              });
            }
          })
      }

    },
    closeRule2 () {
      this.ruleForm2.card = ''
      this.ruleForm2.name = ''
      this.ruleForm2.bank = ''
    },
    submitForm4(formName) {
      let that = this;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.showRefund2 = true;
        } else {
          return false;
        }
      });
    },
    tableSortChange(column) {
      if (column.order === 'descending') {
        this.paramsByInv.sort_str = column.prop
        this.paramsByInv.sort_order = 'desc'
      } else if (column.order === 'ascending'){
        this.paramsByInv.sort_str = column.prop
        this.paramsByInv.sort_order = 'asc'
      } else {
        delete this.paramsByInv.sort_str
        delete this.paramsByInv.sort_order
      }
      if (column.prop == 'process_id') {
        return
      }
      this.loading = true;
      this.$axios
        .get("api/consumer/patent", {
          params: this.paramsByInv
        })
        .then(res => {
          this.loading = false;
          if (res.data.code == 200) {
            this.tableData = res.data.data;
            this.pageSize = res.data.page.per_page;
            this.tableSize = res.data.page.per_page;
            this.tableEnd = res.data.page.per_page;
            this.total = res.data.page.total;
            for (let i = 0; i < this.tableData.length; i++) {
              this.imgs(this.tableData[i])
            }
          } else {
            this.$message.error("错误，请重试");
          }
        })
        .catch(err => {
          this.$message.error(err);
        });
    },
    isInvoice(row) {
      if (!this.showInvoice) {
        this.showRefund3 = false;
      }
      let that = this;
      this.$confirm('<div id="myOrder"><div class="tableTitle"><span class="midText">' +
          '<h3 class="center-title">开票申请须知</h3>' +
          '</span></div>' +
          // '<center>' +
          // '<b class="center-title2">（仅限已缴费用户使用<b class="center-title2">, 未缴费用户请勿申请</b>）</b>' +
          // '</center>' +
          '<br />' +
          '<p style="text-align: left">'+
          '<b class="center-title3">&emsp;&emsp;开票为电子普票，直接发送至开票者邮箱，请确保邮箱可以正常使用</b><br />' +
          '#有疑问请联系：严经理，13164620214</p></div>', '', {
            dangerouslyUseHTMLString: true,
            confirmButtonText: '申请开票',
            cancelButtonText: '取消',
            center: true
          })
        .then(() => {
          that.invoice(row)
        })
        .catch(action => {})
    },
    invoice(row) {
      this.ruleForm.money = row.confirm_money
      this.finalsID = row.id;
      this.ruleForm.name = row.order.liaisons;
      this.ruleForm.email = row.order.liaisons_email;
      this.ruleForm.phone = row.order.liaisons_tel
      this.ruleForm.patent_name = row.order.patent_name
      this.ruleForm.money = row.confirm_money
      this.showInvoice = true;
    },
    invoicingNext(formName) {
      let that = this;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.showInvoice2 = true;
        } else {
          return false;
        }
      });
    },
    submitForm3(formName) {
      let that = this;
      //效验通过
      // that.ruleForm.money =
      let money = parseFloat(that.ruleForm.money)
      console.log(money)
      that.$axios.post('/api/invoice', {
        consumer_id: that.$store.state.user.id,
        channel: that.ruleForm.channel,
        finals_id: that.finalsID,
        taitou: that.ruleForm.taitou,
        tariff_number: that.ruleForm.invoice,
        add_tel: that.ruleForm.add_tel,
        bank_card: that.ruleForm.bank_card,
        money: money,
        send_addr:that.ruleForm.send_addr
      }).then(res => {
        if (res.data.code == 200) {
          that.$message({
            message: '提交申请成功！',
            type: 'success',
            duration: 3000
          });
          // that.verify = false
          that.$refs['ruleForm'].resetFields();
          that.showRefund3 = false
          this.search()
        } else {
          that.$message({
            message: res.data.message,
            type: 'error'
          });
        }
        that.$refs[formName].resetFields();
        that.showInvoice = false;
        that.showInvoice2 = false;
      })

    },
    openInv () {
      // if (this.ruleForm.patent_name.search('协和医院') != -1) {
      //   this.$axios.get('api/inv', {
      //     params: {
      //       taitou: this.ruleForm.patent_user
      //     }
      //   })
      //   .then( res => {
      //     if (res.data.code == 200) {
      //       let data = res.data.data
      //       if (data.length == 1) {
      //         this.ruleForm.taitou = data[0].taitou
      //         this.ruleForm.invoice = data[0].tariff_number
      //       }
      //     } else {

      //     }
      //   })
      // } else {
      //
      // }

      // 根据当前用户的专利权人 查发票信息接口 查的到数据就匹配当前数据的抬头税号查不到就拿开票记录接口 第一条数据匹配
      console.log(this.$store.state.user)
      let params = {
        taitou: this.$store.state.user.liaison.organization,
      }
      this.$axios.get('api/inv', {
        params: params
      }).then(res => {
        if (res.data.code == 200) {
          let data = res.data.data
          if (data.length > 0) {
            this.ruleForm.taitou = data[0].taitou
            this.ruleForm.invoice = data[0].tariff_number
          } else {
            this.$axios.get('api/consumer/invoice', {
                params: {}
            }).then( res => {
                if (res.data.code == 200) {
                  if (res.data.data) {
                    let data = res.data.data[0].invoice
                    this.ruleForm.taitou = data.taitou
                    this.ruleForm.invoice = data.tariff_number
                  }
                }
              })
          }
        }
      })

    },
  }
};
</script>

<style lang="less">
.invoice-main {
  height: 100%; //撑满表格
  #IMTable {
    height: 70%; //撑满表格
  }
  .box-card {
    margin-bottom: 20px;
    .add-invoice {
      float: left;
    }
  }
  .el-autocomplete {
    display: block;
  }
  .pagination {
    margin-top: 30px; /*no*/
  }
}
  .el-main .ivu-poptip .ivu-poptip-popper .ivu-poptip-content .ivu-poptip-inner{
		min-width: 480px ;
		// height: 300px;
		overflow-y:scroll;

	}

	.poptip-condition {
		display: block;
		margin-top: 10px;
		.poptip-condition-item {
			line-height: 25px;
			cursor:pointer;
		}
		.poptip-condition-add {
			font-size: 14px;
		}
	}
	.demo-dynamic {
		padding-left: 10px;
		.el-form-item {
			margin-bottom: 12px;
		}
		.el-input {
			width: 240px;
		}
		.el-date-editor {
			width: 240px;
		}
		.el-button {
			padding: 9px 15px;
			vertical-align: baseline;
		}
		.el-form-item__error {
			padding-top: 0 ;
		}
  }

  .down-execel {
    display: block;
    height: 40px;
    line-height: 40px;
    color: #333333;
    font-size: 14px;
    float: right;
    margin-right: 20px;
  }

	.el-main .poptip-condition .ivu-poptip-popper .ivu-poptip-content .ivu-poptip-inner {
		min-width: 180px;
  }

  .btns {
		margin-top: 10px;
  }
  .file_sh {
    font-size: 26px;
    margin-right: 10px;
  }
  .tag {
    background-color: #f4f4f5;
    color: #909399;
    padding: 10px 16px;
    margin: 0;
    box-sizing: border-box;
    border-radius: 4px;
    overflow: hidden;
    // width: 200px;
    margin-right: 10px;
    // margin-bottom: 10px;
    float: left;
    font {
      font-size: 13px;
      line-height: 18px;
    }
  }
  .processInput {
    display: inline-block !important;
  }
  .applyBilling {
    .el-select {
      width: 100%;
    }
  }
</style>>
